<template>
  <!--发布公告-->
  <div class="page-operate">
    <HeadTop></HeadTop>
    <!-- 位置模块 -->
    <div class="page-head">
      <span class="operate-text">{{title}}</span>
      <div class="operate-box">
        <button @click="submitForm('myForm')" class="submit" v-show="editAble">发布</button>
        <button @click="back()">关闭</button>
      </div>
    </div>
    <div class="content-area">
      <div class="main-content">
        <div class="notice-form">
          <el-form ref="myForm" :model="myForm" :rules="rules" label-width="100px">
            <el-form-item label="公告标题:" prop="title" required>
              <el-input v-model="myForm.title"></el-input>
            </el-form-item>
            <el-form-item label="公告专题:" prop="type" required>
              <el-select v-model="myForm.type" clearable placeholder="--请选择所属专题--"
                         :disabled="type != 'add'">
                <el-option v-for="(item,key,index) in typeArr" :key="item.id" :label=item.label
                           :value=item.value></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="公告正文:" prop="bodys" required>
              <div class="content-wrapper">
                <div class="edit_container">
                  <!-- 图片上传组件辅助-->
                  <el-upload class="avatar-uploader" :action=actionUrl :show-file-list="false"
                             :on-success="uploadSuccess" :on-error="uploadError"
                             :before-upload="beforeUpload">
                  </el-upload>
                  <!--富文本编辑器组件-->
                  <el-row v-loading="quillUpdateImg">
                    <quill-editor class="editer" v-model="myForm.bodys" ref="myQuillEditor" :options="editorOption">
                    </quill-editor>
                  </el-row>
                </div>

              </div>
            </el-form-item>
            <el-form-item label="公告推荐:" prop="areTop">
              <div class='istop-btn'>
                <div :class="isTop == 0 ? 'isTop' : 'noisTop'" @click="isTopChange(0)">开启</div>
                <div :class="isTop == 1 ? 'isTop' : 'noisTop'" @click="isTopChange(1)">不开启</div>
              </div>
            </el-form-item>
            <el-form-item label="封面图片:" prop="image" required>
              <div class="upload-img">
                <img v-if="myForm.image" :src="myForm.image" class="has-img">
                <i v-else class="has-no-img">
                  <img src="/static/img/noImg.png"/>
                </i>
                <el-upload class="upload-btn" :action=actionUrl :show-file-list="false" :on-success="handleUpImgStatus"
                           :before-upload="beforTitleImgUpload">
                  <el-button size="small" type="primary">上传图片</el-button>
                </el-upload>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="scss" type="text/scss">
  @import '../../../style/entry/components/pageChildCommon';
  @import '../../../style/entry/page/noticePush';
</style>
<script>
  import HeadTop from "../../../components/head-top/head-top"
  // 引入富文本编辑器
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  import {quillEditor} from 'vue-quill-editor'
  import com from "../../../js/common"
  import {noticeDetail, noticePush, noticeEdit} from '@/api/getData'

  export default {
    components: {quillEditor, HeadTop},

    data() {
      return {
        title: '发布公告',
        type: 'add',
        isTop: 1,
        hasImg: true,
        editAble: true,
        actionUrl: ``,
        quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
        myForm: {
          type: '',
          title: '',
          bodys: '',
          areTop: '',
          image: '',
          id: ''
        },
        noImgList: [
          {url: '/static/img/noImg.png'}
        ],
        imgList: [],
        typeArr: [
          {
            label: '全部',
            value: '1'
          },
          {
            label: '巡检端',
            value: '2'
          },
          {
            label: '维保端',
            value: '3'
          },
          {
            label: '物业端',
            value: '4'
          }
        ],
        noticeId: '',
        rules: {
          title: [
            {required: true, message: '请输入公告标题'},
          ],
          bodys: [
            {required: true, message: '请输入公告正文'}
          ],
          type: [
            {required: true, message: '请选择公告专题'}
          ],
          image: [
            {required: true, message: '请选择封面图片'}
          ],
        },
        // 上传图片图片路径
        formData: {
          imgUrl: ''
        },

        // 富文本编辑器
        editorOption: {
          placeholder: '',
          theme: 'snow',  // or 'bubble'
          modules: {
            toolbar: {
              container: [
                ['bold', 'underline', 'italic'],
                [{'indent': '-1'}, {'indent': '+1'}],
                [{'align': []}],
                [{'color': []}, {'background': []}],
                [{'font': []}],
                ['clean'],
                ['link', 'image']
              ],  // 工具栏
              handlers: {
                'image': function (value) {
                  if (value) {
                    document.querySelector('.avatar-uploader input').click()
                  } else {
                    this.quill.format('image', false);
                  }
                }
              }
            }
          }
        }
      }
    },
    // 判断操作为添加/查看详情
    mounted() {
      this.actionUrl = com.basePath + '/oss-web/oss/upload';
      // 获取巡查类型数据
      if (this.$route.query.type === 'edit') {
        this.type = this.$route.query.type;
        this.noticeId = this.$route.query.id;
        this.myForm.id = this.$route.query.id;
        this.getNoticeItemData(this.noticeId);
        this.title = '编辑公告';
      }
    },
    methods: {
      // 富文本编辑器
      // 上传图片前
      beforeUpload(file) {
        this.quillUpdateImg = true
        const isRightType = (file.type === 'image/jpeg') || (file.type === 'image/png');
        const isLt5 = file.size / 1024 / 1024 < 5;
        if (!isRightType) {
          this.$message.error('上传头像图片格式不正确!');
          this.quillUpdateImg = false;
        }
        if (!isLt5) {
          this.$message.error('上传头像图片大小不能超过 5MB!');
          this.quillUpdateImg = false;
        }
        return isRightType && isLt5;
      },
      // 上传图片成功
      uploadSuccess(res, file) {
        // res为图片服务器返回的数据
        // 获取富文本组件实例
        let quill = this.$refs.myQuillEditor.quill
        // 如果上传成功
        if (res.code === '200' && res.data !== null) {
          // 获取光标所在位置
          let length = 0;
          let value = file.url;
          // 插入图片  res.info为服务器返回的图片地址
          length = quill.getSelection() != null ? quill.getSelection().index : 0;
          // quill.insertEmbed(length, 'image', value)
          quill.insertEmbed(length, 'image',   `http:${com.uploadUrl}` + res.data);
          // 调整光标到最后
          quill.setSelection(length + 1)
        } else {
          this.$message.error('图片插入失败')
        }
        // loading动画消失
        this.quillUpdateImg = false
      },

      // 上传图片失败
      uploadError(res, file) {
        // loading动画消失
        this.quillUpdateImg = false
        this.$message.error('图片插入失败')
      },

      // 获取页面所需数据
      getNoticeItemData: function (id) {
        noticeDetail({id: id}).then((data) => {
          this.myForm = data.data.data;
          this.isTop = data.data.data.areTop;
        }).catch((err) => {
          this.$message.error({
            message: '查询失败',
            duration: 1500,
          })
        })
      },

      // 图片上传状态
      handleUpImgStatus(res, file) {
        if (file.status == 'success') {
          this.myForm.image = `http:${com.uploadUrl}${res.data}`;
        } else {
          this.$message.error('上传图片失败！');
        }
      },

      // 图片上传的校验
      beforTitleImgUpload(file) {
        const isRightType = (file.type === 'image/jpeg') || (file.type === 'image/png');
        const isLt5 = file.size / 1024 / 1024 < 5;

        if (!isRightType) {
          this.$message.error('上传头像图片格式不正确!');
        }
        if (!isLt5) {
          this.$message.error('上传头像图片大小不能超过 5MB!');
        }
        return isRightType && isLt5;
      },

      // 发布/编辑公告信息时表单数据的校验
      submitForm(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.upNoticeItem();
          } else {
            return false;
          }
        });
      },

      // 发布/编辑公告
      upNoticeItem() {
        let reqData = this.myForm;
        if (this.type == 'add') {
          delete reqData['id'];
          console.log(reqData)
          noticePush(reqData).then((res) => {
            com.mask()
            this.axioThen(this);
          }).catch((err) => {
            this.axioCatch(this, err);
          })
        } else {
          noticeEdit(reqData).then((res) => {
            com.mask()
            this.axioThen(this);
          }).catch((err) => {
            this.axioCatch(this, err);
          })
        }
      },

      // 編輯/添加公告成功後的操作
      axioThen(self) {
        self.$message.success({
          message: '操作成功',
          duration: 1500,
          onClose: () => {
            com.unmask()
            self.$router.push('/manage/noticeMgr/noticeLists')
          }
        });
      },

      // 編輯/添加公告失敗後的操作
      axioCatch(self, err) {
        if (self.type == 'edit' && err.data.code == '501') {
          self.$message.error('操作失败: ' + '当前暂无推荐位，请在公告列表编辑后再推荐')
        } else {
          self.$message.error('操作失败: ' + err.data.data)
        }
      },

      // 是否推荐切换
      isTopChange(val) {
        this.isTop = val;
        this.myForm.areTop = val;
      },

      // 返回上一级
      back() {
        this.$router.go(-1);
      },
    }
  };
</script>


